import { Body, Controller, Get, Param, Patch, Post } from '@nestjs/common';
import { BaseController } from '@/controllers/base.controller';
import { AutotradingService } from '@/services/autotrading.service';
import { halt, ok } from "@/utils";
import {
  AssetAutoTradingCreateDto,
  AssetAutoTradingQueryDto,
  AssetAutoTradingUpdateDto,
} from '@/dtos/autotrading.dto';

@Controller('autotrading')
export class AutotradingController extends BaseController {
  constructor(
    private readonly AutotradingService: AutotradingService,
  ) {
    super();
  }

  @Get('admin/status')
  async status() {
    const queueCache = await this.redis.exists('bull:autotrading:repeat');
    if (!queueCache) {
      return ok(0);
    } else {
      return ok(1);
    }
  }

  @Get('admin/switch')
  async witch() {
    const queueCache = await this.redis.exists('bull:autotrading:repeat');
    if (!queueCache) {
      await this.AutotradingService.start();
      return ok(1);
    } else {
      await this.AutotradingService.close();
      return ok(0);
    }
  }

  @Get('admin/cache/:assetId')
  async cache(@Param('assetId') assetId: number) {
    // 查询自动交易详情
    const detail = await this.AutotradingService.detail(assetId);

    let status;
    if (detail.status == false) {
      if (!detail.sellerId) {
        return halt('挂售账户异常');
      }
      const res = await this.AutotradingService.cache(assetId, detail.sellerId);
      if (!res) {
        return halt('缓存队列异常，检查是否持有藏品');
      }
      status = true;
    } else {
      const res = await this.AutotradingService.clean(assetId);
      if (!res) {
        return halt('清除队列异常');
      }
      status = false;
    }

    return ok(
      await this.AutotradingService.update({
        where: {
          assetId,
        },
        data: {
          status: status,
        },
      }),
    );
  }

  @Post('admin/query')
  async query(@Body() dto: AssetAutoTradingQueryDto) {
    return ok(await this.AutotradingService.query(dto));
  }

  @Post('admin/create')
  async create(@Body() dto: AssetAutoTradingCreateDto) {
    return ok(await this.AutotradingService.create(dto.data));
  }

  @Patch('admin/update')
  async update(@Body() dto: AssetAutoTradingUpdateDto) {
    return ok(await this.AutotradingService.update(dto));
  }
}
